package cn.maydaymemory.mastery.configuration;

import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ConfigurationManager{
    private Map<File, YamlConfiguration> configurationMap = new HashMap<>();
    private JavaPlugin plugin;

    public ConfigurationManager(JavaPlugin plugin){
        this.plugin=plugin;
    }

    public void reload(File configPath){
        if(configPath.isDirectory()) return;
        if( !configPath.getParentFile().exists() && !configPath.getParentFile().mkdirs() ) return;
        YamlConfiguration config = new YamlConfiguration();
        if (!configPath.exists()) {
            try {
                if (configPath.createNewFile()) {
                    InputStream input = plugin.getResource(configPath.getName());
                    if (input != null) {
                        OutputStream output = new FileOutputStream(configPath);
                        byte[] b = new byte[1024];
                        int length;
                        while ((length = input.read(b)) != -1) {
                            output.write(b, 0, length);
                        }
                        output.flush();
                        output.close();
                        config.load(configPath);
                        input.close();
                    }
                }
            } catch (InvalidConfigurationException | IOException e) {
                e.printStackTrace();
            }
        }else config = YamlConfiguration.loadConfiguration(configPath);
        configurationMap.put(configPath,config);
    }

    public void save(File configPath){
        YamlConfiguration config=configurationMap.get(configPath);
        if(config==null) return;
        try {
            config.save(configPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public FileConfiguration getConfig(File configPath) {
        if(!configurationMap.containsKey(configPath)) reload(configPath);
        return configurationMap.get(configPath);
    }
}
